<?php
error_reporting(0);
require_once APPLICATION_PATH . '/../library/TaobaoSdk/TopSdk.php';

class Uuch_Reader_TaobaoReader extends Uuch_Reader_ProductReader {

    private $_appkey = '21170405';
    private $_front_appkey = '21170405';                                //前台的appkey
    private $_front_secretKey = 'e7b2c2be477fcd7196e40c1f8b81a0ee';     //前台的secreKey
    private $_taoBao_Nick = 'uuchcn';//'maculasoft';                            //计算佣金的淘宝帐号
    private $_secretKey = 'e7b2c2be477fcd7196e40c1f8b81a0ee';

    public function request($url, $params, $method = 'POST') {
        $client = new Zend_Http_Client($url);
        $client->setConfig(array('timeout' => 60));
        if ($method == 'POST') {
            $client->setParameterPost($params);
        } else {
            $client->setParameterGet($params);  
        }
        $response = $client->request($method);
        $respObject = @simplexml_load_string($response->getBody());
        return $respObject;
    }

    public function getInfo($url) {
        set_time_limit(180);

        $resp = $this->request('http://127.0.0.1/tbsdk/ItemGetRequest.php', array(
            'id' => $this->getId($url),
            
        ));
        
        $uri = parse_url($url);      
        if(preg_match('{(.*\.m\.)(.*)}', $uri['host'], $arr) || preg_match('{(m\..*?\.)(.*)}', $uri['host'], $arr)){
            $urlitemid = $this->getId($url);
             if ($arr[2] == 'taobao.com') {
                $url = 'http://item.taobao.com/item.htm?id=' . $urlitemid; 
             }
             if ($arr[2] == 'tmall.com') {
                $url = 'http://detail.tmall.com/item.htm?id=' . $urlitemid; 
             }
         }
   
//        var_dump($resp);exit;
        $promotions = null;      

        $product = new Application_Model_Product();

        if ($promotions == NULL && gettype($promotions) != 'array') {
            $promotions = array();
            $product->PromotionError = true;
        } else {
            $product->PromotionError = FALSE;
        }

        $code = (string) $resp->code;
        if ($code != "")
            return NULL;

        $product->Name = (string) $resp->item->title;
        $product->Price = (string) ($resp->item->price);
        if (array_key_exists('price', $promotions)) {
            $product->Price = $promotions['price'];
        }
        $favorablePriceSuk = $this->getSalesPrice($this->getId($url));
//        var_dump($price);
//        $product->Price = $product->Price<=$price?$product->Price:$price;
        $product->Price = $favorablePriceSuk["price"]=="99999"?$product->Price:$favorablePriceSuk["price"];
        
        $product->RemoteImage = (string) $resp->item->pic_url;
        $product->Image = (string) $resp->item->pic_url;
        $product->ShipFee = $this->minPostFee($resp, (string) $resp->item->nick);
        $product->Url = $url;
        $desc= preg_replace('/style=\"[^\"]+\"/',"  ", (string) $resp->item->desc);
        $desc = preg_replace('/width=\"[^\"]+\"/', "width=\"100%\"", $desc);
        $product->Description = $desc;
        $product->PropertyAlias = urldecode((string) $resp->item->property_alias);
        $product->Quantity = (string) $resp->item->num;

        if ($resp->item->prop_imgs) {
            $images = '';
            foreach ($resp->item->prop_imgs->prop_img as $prop_img) {
                $images = $images . $prop_img->properties . '##' . $prop_img->url . ';';
            }
            $product->PropertyImages = rtrim($images, ';');
        }
        if ($resp->item->skus) {
            
            foreach ($resp->item->skus->sku as $sku) {
                $psku = new Application_Model_Sku();
                $psku->SkuNo = (string) $sku->sku_id;
                $skuPrice = (string) $sku->price;
                if (array_key_exists($psku->SkuNo, $promotions)) {
                    $skuPrice = $promotions[$psku->SkuNo];
                }
                $price = "99999";
                if($favorablePriceSuk["skus"]){
                    $price = $this->getSkusFavorablePrice($sku->sku_id, $favorablePriceSuk["skus"]);
                }
                $psku->Price = $price=="99999"?$skuPrice:$price;
                $psku->Quantity = (string) $sku->quantity;
                $psku->DateCreated = date('Y-m-d H:i:s');
                $psku->Properties = (string) $sku->properties_name;
                $product->addSku($psku);
            }
            $product->HasSkus = TRUE;
        }

        $product->sku = $this->getId($url);
        if (!$product->Price) {
            return NULL;
        }
        $shop = Application_Model_Shop::getByName((string) $resp->item->nick);
        if ($shop == NULL) {
            $shop = new Application_Model_Shop();
            $shop->Name = (string) $resp->item->nick;
            $shop->IsTaobao = true;
            $shop->Url = $product->Url;

            $shop->save();
        }
        $product->ShopId = $shop->Id;
        $product->save();

        return $product;
    }
    
    public function getInfoForNew($url) {
        set_time_limit(180);
        
        $uri = parse_url($url); 
        //抓取国际版淘宝的商品
          //抓取国际版淘宝的商品
        if($uri['host'] == 'world.taobao.com' || $uri['host'] == 'tw.taobao.com'){
            $regex = explode('/',$uri['path']);
            $wid = substr($regex[count($regex)-1],0,-4);
            $resp = $this->request('http://127.0.0.1/tbsdk/ItemGetRequest.php', array(
            'id' => $wid,
            ));
            $url = "http://$uri[host]/item/$wid.htm?$uri[query]&id=".$wid;
        }else{
            $resp = $this->request('http://127.0.0.1/tbsdk/ItemGetRequest.php', array(
                'id' => $this->getId($url),
            ));
        }
        if(preg_match('{(.*\.m\.)(.*)}', $uri['host'], $arr) || preg_match('{(m\..*?\.)(.*)}', $uri['host'], $arr)){
            $urlitemid = $this->getId($url);
             if ($arr[2] == 'taobao.com') {
                $url = 'http://item.taobao.com/item.htm?id=' . $urlitemid; 
             }
             if ($arr[2] == 'tmall.com') {
                $url = 'http://detail.tmall.com/item.htm?id=' . $urlitemid; 
             }
         }
        $promotions = null;       

        $product = new Application_Model_Product();

        if ($promotions == NULL && gettype($promotions) != 'array') {
            $promotions = array();
            $product->PromotionError = true;
        } else {
            $product->PromotionError = FALSE;
        }

        $code = (string) $resp->code;
        if ($code != "")
            return NULL;

        $product->Name = (string) $resp->item->title;
        $product->Price = (string) ($resp->item->price);
        if (array_key_exists('price', $promotions)) {
            $product->Price = $promotions['price'];
        }
        $favorablePriceSuk = $this->getSalesPrice2($url);
        $product->Price = $favorablePriceSuk["price"]=="99999"?$product->Price:$favorablePriceSuk["price"];
        
        $product->RemoteImage = (string) $resp->item->pic_url;
        $product->Image = (string) $resp->item->pic_url;
        $product->ShipFee = $this->minPostFee($resp, (string) $resp->item->nick);
        $product->Url = $url;
        $desc = preg_replace('/width=\"[^\"]+\"/', "width=\"100%\"", (string) $resp->item->desc);
        $product->Description = $desc;       
        $product->PropertyAlias = urldecode((string) $resp->item->property_alias);
        $product->Quantity = (string) $resp->item->num;       
        if ($resp->item->prop_imgs) {
            $images = '';
            foreach ($resp->item->prop_imgs->prop_img as $prop_img) {
                $images = $images . $prop_img->properties . '##' . $prop_img->url . ';';
            }
            $product->PropertyImages = rtrim($images, ';');
        }
        if ($resp->item->skus) {            
            foreach ($resp->item->skus->sku as $sku) {
                $psku = new Application_Model_Sku();
                $psku->SkuNo = (string) $sku->sku_id;
                $skuPrice = (string) $sku->price;
                if (array_key_exists($psku->SkuNo, $promotions)) {
                    $skuPrice = $promotions[$psku->SkuNo];
                }
                $price = "99999";
                if($favorablePriceSuk["skus"]){
                    //$price = $this->getSkusFavorablePrice($sku->sku_id, $favorablePriceSuk["skus"]);
                    $price = $this->getSkusFavorablePrice2((string)$sku->properties, $favorablePriceSuk["skus"]);
                }
                $psku->Price = $price=="99999"?$skuPrice:$price;
                $psku->Quantity = (string) $sku->quantity;
                $psku->DateCreated = date('Y-m-d H:i:s');
                $psku->Properties = (string) $sku->properties_name;
                $product->addSku($psku);
            }
            $product->HasSkus = TRUE;
        }

        $product->sku = $this->getId($url);
        if (!$product->Price) {
            return NULL;
        }

        $shop = Application_Model_Shop::getByName((string) $resp->item->nick);
        if ($shop == NULL) {
            $shop = new Application_Model_Shop();
            $shop->Name = (string) $resp->item->nick;
            $shop->IsTaobao = true;
            $shop->Url = $product->Url;

            //$shop->save();
        }
        //$product->ShopId = $shop->Id;
        //$product->save();

        return array(
            'product' => $product, 
            'shopName' => (string) $resp->item->nick,
            'siteName' => stripos($uri['host'], 'taobao') === false ? '天猫' : '淘宝',
            'shopUrl' => $url,
            'url' => $url,
            'item_imgs'=>$resp->item->item_imgs,
            'siteUrl' => $uri['scheme'] . '://' . $uri['host']);
    }
    
    private function getSalesPrice($id)
    {

        $url = "http://mdskip.taobao.com/core/initItemDetail.htm?itemId=".$id;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_ENCODING, "" );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.tmall.com' );
        curl_setopt($ch, CURLOPT_AUTOREFERER, true );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );   
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10 );
        curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
        $html = curl_exec($ch);
        $response = curl_getinfo($ch);
        curl_close($ch); 
        $htmlA = @iconv("GB2312", 'UTF-8', trim($html));
        if(preg_match('/\w:/', $htmlA)){
            $htmlA = preg_replace('/{(\w+):/is', '{"$1":', $htmlA);
            $htmlA = preg_replace('/,(\w+):/is', ',"$1":', $htmlA);
        }
        $htmlB = json_decode($htmlA);

        //$htmlB = $this->getPreferentialPrice($id);

        $minPrice = 99999;
        if($htmlB){
            foreach ($htmlB->defaultModel->itemPriceResultDO->priceInfo as $key => $value) {
                if($value->promotionList){
                    foreach ($value->promotionList as $key1 => $value1) {
                        if($value1->type != "店铺vip"){
                            $minPrice = $value1->price<=$minPrice?$value1->price:$minPrice;
                        }
                    }
                }
            }
  
            return array("price" => $minPrice,"skus" => $htmlB->defaultModel->itemPriceResultDO->priceInfo);
        } 
        return array("price" => $minPrice,"skus" =>false);
    }
    
    /**
     * 获取优惠价
    */
    function getPreferentialPrice($id)
    {
        if(empty($id)){
            return false;
        }

        $htmlB = null;
        $priceServiceUrl = array(
                            // "http://tb.wt615.com/price.php?id=" . $id,
                            "http://tb.silule.com/price.php?id=" . $id,
                            "http://wl.mosuda.com/fms/admin/ws_rec_waybill!getTaobao.action?taobaoid=" . $id,
                        );
        //打乱顺序
        shuffle($priceServiceUrl);
        //uuch自己服务器调用
        $url  = "https://mdskip.taobao.com/core/initItemDetail.htm?itemId=".$id;
        $data = array (                 
                "Referer: https://detail.tmall.com/item.htm?id=".$id,
                "Host: mdskip.taobao.com"
            );
        $ch = curl_init($url); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $data); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $html = curl_exec($ch);
        curl_close($ch);
        $htmlA = @iconv("GB2312", 'UTF-8', trim($html));
        if(preg_match('/\w:/', $htmlA)){
            $htmlA = preg_replace('/{(\w+):/is', '{"$1":', $htmlA);
            $htmlA = preg_replace('/,(\w+):/is', ',"$1":', $htmlA);
        }
        $htmlB = json_decode($htmlA);
        if(empty($htmlB)){
            try {
                foreach ($priceServiceUrl as $k => $url) {
                    $ch = curl_init($url); 
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                    $html = curl_exec($ch);
                    $htmlA = @iconv("GB2312", 'UTF-8', trim($html));
                    if(preg_match('/\w:/', $htmlA)){
                        $htmlA = preg_replace('/{(\w+):/is', '{"$1":', $htmlA);
                        $htmlA = preg_replace('/,(\w+):/is', ',"$1":', $htmlA);
                    }
                    $htmlB = json_decode($htmlA);
                    if(!empty($htmlB)){
                        break;
                    }
                }
            } catch (Exception $e) {
                //日志
            } finally {
                curl_close($ch);
            }
        }
        return $htmlB;
    }

    private function getSkusFavorablePrice($skuNo,$favorableSkusArrPrice)
    {
        $minPrice = 99999;
        foreach ($favorableSkusArrPrice as $skuKey => $favorablePriceVal) {
            if($skuKey == $skuNo && $favorablePriceVal->promotionList){
                foreach ($favorablePriceVal->promotionList as $key1 => $priceVal) {
                        $minPrice = $priceVal->price<=$minPrice?$priceVal->price:$minPrice;
                }
            }
            if(isset($favorablePriceVal->suggestivePromotionList)){
                if(99999 == $minPrice && $favorablePriceVal->suggestivePromotionList && $skuKey == $skuNo){
                    foreach ($favorablePriceVal->suggestivePromotionList as $k => $v) {
                            $minPrice = $v->price<=$minPrice?$v->price:$minPrice;
                    }
                }
            }
        }
        return $minPrice;
    }
     private  function getSalesPrice2($url)
    {
        $url="http://www.lete.com/usys/grab/grab.php?url=".urlencode($url); 
        $ch = curl_init($url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $html = curl_exec($ch);
        $htmlA=preg_replace('/\n/is', '', $html);
        if(preg_match('/\w:/', $htmlA)){
            $htmlA = preg_replace('/{(\w+):/is', '{"$1":', $htmlA);
            $htmlA = preg_replace('/,(\w+):/is', ',"$1":', $htmlA);
        }                    
        $htmlB = json_decode($htmlA);       
        if($htmlB){
            $skus=json_decode($htmlB->json_sSkusetinfo,true);
            return array("price" =>$htmlB->price,"skus" => $skus);
        } 
        return array("price" => $minPrice,"skus" =>false);
    }
    private function getSkusFavorablePrice2($skuNo,$favorableSkusArrPrice)
    {
        $minPrice = 99999; 
        $skuNo=str_replace(';', ':', $skuNo); 
        $arrsku=explode(':', $skuNo);       

        foreach ($favorableSkusArrPrice as $skuKey => $price) { 
                if($this->is_exist($skuKey, $arrsku)){                  
                   $minPrice =$price;break;
                 }    
        }
        return $minPrice;
    }
    public function is_exist($str,$key){
     $bool=true;
     foreach($key as $v){      
      if(strpos($str,$v)>-1){
        
      }else{
          return false;
      }
     }    
     return $bool;
    }

    public function getPromotion($id) {
        $prices = $this->getPromotionByHtml($id);
        if($prices){
            return $prices;
        }
        return $this->getPromotionByApi($id);
    }
    
    public function getPromotionByHtml($id){
        try{
            $result = array();
            $html = file_get_contents('http://a.m.tmall.com/ajax/sku.do?item_id=' . $id);
//            var_dump($html);exit;
            $prires = json_decode($html);
            if(!isset($prires->availSKUs)){
                return NULL;
            }
            $skus = get_object_vars( $prires->availSKUs);
            foreach ($skus as $item){
                if(isset($item->promoPrice) && is_numeric($item->promoPrice)){
                    $result[$item->skuId] = $item->promoPrice;
                }else{
                    $result[$item->skuId] = $item->price;
                }
                if(array_key_exists('price', $result)){
                    if($result['price']>$result[$item->skuId]){
                        $result['price'] = $result[$item->skuId];
                    }
                }else{
                    $result['price'] = $result[$item->skuId];
                }
            }
            
            return $result;
        }  catch (Exception $ex){
            var_dump($ex);
            exit;
            return NULL;
        }
        
    }

    public function getPromotionByApi($id) {
        /*$client = new TopClient();
        $client->appkey = $this->_appkey;
        $client->secretKey = $this->_secretKey;
        $req = new UmpPromotionGetRequest;
        $req->setItemId($id);
        $resp = $client->execute($req);*/

$resp = $this->request('http://127.0.0.1/tbsdk/UmpPromotionGetRequest.php', array(
            'id' => $id,            
        ));

    /*$resp = $this->request('http://121.199.174.216:30002/api/UmpPromotion/GetUmpPromotionInfo', array(
            'productId' => $id,
        ));*/

        if (!isset($resp->promotions))
            return null;

        $prices = array();
        if ($resp->promotions && !$resp->promotions->promotion_in_item) {
            return $prices;
        }
//        var_dump($resp);exit;
        if ($resp->promotions->promotion_in_item && $resp->promotions->promotion_in_item->promotion_in_item) {
            foreach ($resp->promotions->promotion_in_item->promotion_in_item as $item) {
                //如果是店铺VIP价格，则跳过
                if (strpos('-' . (string) $item->promotion_id, 'shopvip') > 0) {
                    continue;
                    ;
                }

                $prices['price'] = floatval($item->item_promo_price);
                
                $tempprice = array();
                if ($item->sku_price_list) {
                    //获取促销价
                    foreach ($item->sku_price_list->price as $price) {
                        $tempprice[] = floatval($price);
                    }
                    $i = 0;
                    //取对应SKU的最低促销价格
                    foreach ($item->sku_id_list->string as $sku) {
                        if (array_key_exists((string) $sku, $prices)) {
                            if ($prices[(string) $sku] > $tempprice[$i]) {
                                $prices[(string) $sku] = $tempprice[$i];
                            }
                        } else {
                            $prices[(string) $sku] = $tempprice[$i];
                        }
                        $i++;
                    }
                }
            }
        }
        if (count($prices) > 0)
            $prices['price'] = min($prices);

        foreach ($prices as $sku => $value) {
            $prices[$sku] = sprintf("%01.2f", $prices[$sku]);
        }
        return $prices;        
    }

    /**
     * 从商品网址中间提取ID
     * @param type $url
     * @return type 
     */
    public function getId($url) {
        $id = '';
        $queryId = array('id', 'mallstItemId', 'item_id', 'default_item_id');

        $regexs = array();
        if (preg_match('/http:\/\/a.m.taobao.com\/i(\d+).htm/', $url, $regexs)) {
            $id = $regexs[1];
        } else if (preg_match('/http:\/\/a.m.tmall.com\/i(\d+).htm/', $url, $regexs)) {
            $id = $regexs[1];
        } else {
            $urlInfo = parse_url($url);
            if($urlInfo['host'] == 'detail.ju.taobao.com'){
                if(preg_match('/item_id=\d+/', $url, $regexs))
                    $params    = explode("=", $regexs[0]);
                    if(is_numeric($params[1])){
                        $id = $params[1];
                    }
            }
            if($urlInfo['host'] == 'world.tmall.com' || $urlInfo['host'] == 'world.taobao.com' || $urlInfo['host'] == 'tw.taobao.com'){
                $regex = explode('/',$urlInfo['path']);
                $id = substr($regex[count($regex)-1],0,-4);
            }
            if(!is_numeric($id)){
                foreach ($queryId as $query) {
                    $id = $this->query($url, $query);
                    if ($id != NULL)
                        break;;
                }
            }
        }

        return $id;
    }

    /**
     * 计算商品所需要的运费，取运费最少的方式
     * @param type $resp
     * @param type $userNick
     * @return type 
     */
    public function minPostFee($resp, $userNick) {
        //如果是卖家承担运费，则直接返回0
        if ($resp->item->freight_payer == 'seller') {
            return 0;
        }

        $weight = 0;
        if ($resp->item->item_weight) {
            $weight = (string) $resp->item->item_weight;
        }
        
        $post = array();
        if ($resp->item->ems_fee && (string) $resp->item->ems_fee != '0') {
            $post[] = (string) $resp->item->ems_fee;
        }

        if ($resp->item->express_fee) {
            $post[] = (string) $resp->item->express_fee;
        }

        if ($resp->item->post_fee && count($post) == 0) {
            $post[] = (string) $resp->item->post_fee;
        }
        
        $postid = (string) $resp->item->postage_id;
        
        if ($postid && $postid != '0') {
            $post = array();
        } else {
            return min($post);
        }
        
        /*$rep = new DeliveryTemplateGetRequest();
        $rep->setFields('template_id,template_name,created,modified,supports,assumer,valuation,query_express,query_ems,query_cod,query_post');
        $rep->setTemplateIds($postid);
        $rep->setUserNick($userNick);

        $client = new TopClient();
        $client->appkey = '21363005';
        $client->secretKey = '72905e19dbd8ef6c33ab002ecdd04ccd';

        $response = $client->execute($rep);*/

        //监控访问的IP
        // $ip=$this->getIP();
        // $taobaoip=new Application_Model_taobaoip;
        // $ipresult = Application_Model_taobaoip::getByIp($ip);
        // if($ipresult){
        //     $count=$ipresult->count;
        //     $ipresult->count = $count+1;
        //     $ipresult->save();
        // }else{
        //     $taobaoip->ip = $ip;
        //     $taobaoip->type = 'minPostFee';
        //     $taobaoip->count = 1;
        //     $taobaoip->save();
        // }
    // if(rand(1,2)==1){
    //     $key='23087405';
    //     $secret='a7769177387563c5b2b6ec4daac7e82b';
    // }else{
    //     $key='23091581';
    //     $secret='d8da761a3ac92611aea7ea55f8f217a2';
    // }
// $response = $this->request('http://127.0.0.1/tbsdk/DeliveryTemplateGetRequest.php', array(
//          'appkey' => '12317175',
//          'secretKey' => '141c3281b44156f19a8c5a12d408edb4',
            
//           // 'appkey' => '23148888',
//           // 'secretKey' => '6f2ace5e8e6f332dc667ea802852e95e',
//             //'appkey' => '23098996',
//             //'secretKey' => '2bb019f77b7c6395e50ebcccf5e67374',
//             // 'appkey' => $key,
//             // 'secretKey' => $secret,

//          'userNick'   => $userNick,
//          'templateId' => $postid
//      ));

    /*$response = $this->request('http://121.199.174.216:30002/api/DeliverTemplate/GetDeliverTemplateInfo', array(
            'userNick' => $userNick,
            'templateId' => $postid
        ));*/   

        $szPost = array();
        $gdPost = array();
        $cnPost = array();
//        var_dump($response->delivery_templates);exit;
        // foreach ($response->delivery_templates as $deliv) {
        //     foreach ($deliv->delivery_template->fee_list->top_fee as $fee) {
        //         $dest = (string) $fee->destination;
        //         $destArray = explode(',', $dest);
        //         //如果有深圳市就添加此运费并返回
        //         if (in_array('440300', $destArray)) {
        //             $szPost[(string) $fee->service_type] = $this->cult_shipfee($weight, $fee);
        //             continue;
        //         }
        //         //如果有广东省就添加此运费并返回
        //         if (in_array('440000', $destArray)) {
        //             $gdPost[(string) $fee->service_type] = $this->cult_shipfee($weight, $fee);
        //             continue;
        //         }
        //         //否则就取默认的运费
        //         if (in_array('1', $destArray)) {
        //             $cnPost[(string) $fee->service_type] = $this->cult_shipfee($weight, $fee);
        //             continue;
        //         }
        //     }
        // }
        
        foreach ($gdPost as $key => $value) {
            $cnPost[$key] = $value;
        }

        foreach ($szPost as $key => $value) {
            $cnPost[$key] = $value;
        }

        $itemid = (string)$resp->item->num_iid;
        $html = file_get_contents('https://delivery.taobao.com/detail/delivery_detail.do?_ksTS=1383547947679_6848&callback=jsonp6849&itemId='.$itemid.'&source=cdetail&areaId=440300');
        // $html = iconv("gb2312","UTF-8",$html);
        // $arrCon1 = explode("{'default':'", $html);
        // $arrCon2 = explode("'},'consignAssignment'", $arrCon1[1]);
        $arrCon1 = explode("{\"default\":\"", $html);
        $arrCon2 = explode("\"}", $arrCon1[1]); 
        if(strpos($arrCon2[0],"免运费")){
            $shipFee[] = 0;
        } else {
            $arrFee = explode(": ", $arrCon2[0]);
            for ($index = 0; $index < count($arrFee); $index++) {
                if($index>0){
                    $shipFee[] = trim(substr($arrFee[$index], 5,5));
                }
            }
        }
        
          /*
         *临时接口用不了，暂时使用这个方法获取运费
        */
        if($response->msg){
            if((string) $resp->item->post_fee){
                $cnPost[(string) $fee->service_type]=(string) $resp->item->post_fee;
            }
        }

        if (count($cnPost) > 0)
            if(min($cnPost)>50){
                return min($cnPost)>min($shipFee)?min($shipFee):min($cnPost);
            } else {
                return min($cnPost);
            }
        else {
            if(count($shipFee)>0){
                return min($shipFee);
            }else{
                return 0;
            }
        }
    }

    private function cult_shipfee($weight, $shipfee) {
        if ($weight == 0) {
            return (string) $shipfee->start_fee;
        }

        $addWeight = ($weight - (string) $shipfee->start_standard) * 1000;
        if ($addWeight <= 0) {
            return (string) $shipfee->start_fee;
        }

        $mod = $addWeight % (1000 * (string) $shipfee->add_standard);
        $times = ($addWeight - $mod) / ((string) $shipfee->add_standard * 1000) + ($mod > 0 ? 1 : 0);
        return (string) $shipfee->start_fee + intval($times) * (string) $shipfee->add_fee;
    }

    /**
     * 功能：
     *          获取商品的淘宝客推广URL
     * 
     * 处理逻辑：
     *          1、判断OrderItem中,taoBalUrl是否为空，空则调用API获取，不空则直接返回taoBaoUrl
     *          2、taoBaoUrl不为空时，则调用TaobaokeItemsGetRequest，传入appkey、secretKey、$productName、taoBaoNick
     *          3、根据返回的taobaokeItem XML数据，为空则没有推广URL；不为空，则判断返回的item中的num_iid是否与商品代购URL中的id相同，取相同的推广URL
     * 
     * 参数：
     * @param [in]      type $product     商品名称
     * @param [in]      type $url         商品购物URL
     * 
     * 返回：
     * @return string URL   推广URL
     */
    public function getTopUrl($productName, $url) {
        if ($url == NULL) {
            return "";
        }
        $arr = parse_url($url);
        if (isset($arr['query'])) {
            $query = $arr['query'];
        } else {
            return "";
        }
        $queryParts = explode('&', $query);

        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            if (isset($item[1]))
                $params[$item[0]] = $item[1];
        }

        if (!isset($params["id"])){
            $params["id"] = $this->getId($url);
            if (!isset($params["id"]))
               return "";
        }
        $url_id = $params["id"];
        if ($productName != NULL) {
            /*$c = new TopClient;
            $c->appkey = $this->_front_appkey;
            $c->secretKey = $this->_front_secretKey;
            $req = new TaobaokeItemsGetRequest;
            $req->setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
            if (strpos($url, ".tmall.com", 0) > -1)
                $req->setMallItem("true");
            $req->setNick($this->_taoBao_Nick);        //佣金的淘宝帐号
            $req->setKeyword($productName);
            $resp = $c->execute($req);*/

$resp = $this->request('http://127.0.0.1/tbsdk/TaobaokeItemsGetRequest.php', array(
                'nick' => $this->_taoBao_Nick,
                'keyword' => $productName,
                'mallitem' => strpos($url, ".tmall.com", 0) > -1 ? 1 : 0
            ));

    /*$resp = $this->request('http://121.199.174.216:30002/api/TaobaoKe/GetTaobaoKeInfo', array(
                'SearchKeyword' => $productName,
            ));*/

            if ($resp != NULL) {
                if ($resp->total_results >= 1) {
                    if ($resp->total_results == 1) {
                        //返回单个XML Item时，直接对比商品代购URL的id与返回的Taoboke id是否相等
                        $num_iid = (string) $resp->taobaoke_items->taobaoke_item->num_iid;
                        if ($num_iid == $url_id) {
                            return (string) $resp->taobaoke_items->taobaoke_item->click_url;
                        }
                    } else {
                        //返回多个Item时，则对比URL中的id，取相同的click_url；没有则不取.
                        $total_results = (int) $resp->total_results;
                        for ($i = 0; $i < $total_results; $i++) {
                            $temp_num_iid = (string) $resp->taobaoke_items->taobaoke_item[$i]->num_iid;
                            if ($url_id == $temp_num_iid) {
                                return (string) $resp->taobaoke_items->taobaoke_item[$i]->click_url;
                            }
                        }
                    }
                }
            }
        }

        return "";
    }
    
    public function getOneTopUrl($productName, $url) {
        if ($url == NULL) {
            return "";
        }
        $arr = parse_url($url);
        if (isset($arr['query'])) {
            $query = $arr['query'];
        } else {
            return "";
        }
        $queryParts = explode('&', $query);

        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            if (isset($item[1]))
                $params[$item[0]] = $item[1];
        }
//        var_dump($params["id"]);exit;
        if (!isset($params["id"]))
            return '';
        $url_id = $params["id"];
        if ($productName != NULL) {
            /*$c = new TopClient;
            $c->appkey = $this->_front_appkey;
            $c->secretKey = $this->_front_secretKey;
            $req = new TaobaokeItemsGetRequest;
            $req->setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
            if (strpos($url, ".tmall.com", 0) > -1)
                $req->setMallItem("true");
            $req->setNick($this->_taoBao_Nick);        //佣金的淘宝帐号
            $req->setKeyword($productName);
            $resp = $c->execute($req);*/

$resp = $this->request('http://127.0.0.1/tbsdk/TaobaokeItemsGetRequest.php', array(
                'nick' => $this->_taoBao_Nick,
                'keyword' => $productName,
                'mallitem' => strpos($url, ".tmall.com", 0) > -1 ? 1 : 0
            ));
    
    /*$resp = $this->request('http://121.199.174.216:30002/api/TaobaoKe/GetTaobaoKeInfo', array(
                'SearchKeyword' => $productName,
            ));*/

            if ($resp != NULL) {
                if ($resp->total_results >= 1) {
                    if ($resp->total_results == 1) {
                        //返回单个XML Item时，直接对比商品代购URL的id与返回的Taoboke id是否相等
                        $num_iid = (string) $resp->taobaoke_items->taobaoke_item->num_iid;
                        if ($num_iid == $url_id) {
                            return (string) $resp->taobaoke_items->taobaoke_item->click_url;
                        }
                    } else {
                        //返回多个Item时，则对比URL中的id，取相同的click_url；没有则不取.
                        $total_results = (int) $resp->total_results;
                        for ($i = 0; $i < $total_results; $i++) {
                            $temp_num_iid = (string) $resp->taobaoke_items->taobaoke_item[$i]->num_iid;
                            if ($url_id == $temp_num_iid) {
                                return (string) $resp->taobaoke_items->taobaoke_item[$i]->click_url;
                            }
                        }
                    }
                }
            }
        }

        return "";
    }

    public function taobaowlxx($tid) {
       // $appkey = "23087578";
        //$secretKey = "9091c68da02bddfcda0c8fb91458cf83";
        
        // $appkey = '23148888';
        // $secretKey = '6f2ace5e8e6f332dc667ea802852e95e';
        if(date('G')=='9' || date('G')=='10' || date('G')=='16' || date('G')=='17'){
            // $appkey = '23148888';
            // $secretKey = '6f2ace5e8e6f332dc667ea802852e95e';
            $appkey = '23090235';
            $secretKey = 'd11e4e30490f9f142f3b5dd6fae86ae2';
        }else{
            $appkey = '23090235';
            $secretKey = 'd11e4e30490f9f142f3b5dd6fae86ae2';
        }
        $sign = substr($tid, -4);
        $taobaoapi = Application_Model_Taobaoapi::getByTaoBaoSign($sign);
        $sessionKey = $taobaoapi->sessionkey;
        /*$c = new TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secretKey;
        $req = new TradeFullinfoGetRequest;
        $req->setFields("orders.logistics_company,orders.invoice_no, consign_time");
        $req->setTid($tid);
        $resp = $c->execute($req, $sessionKey);*/

$resp = $this->request('http://127.0.0.1/tbsdk/TradeFullinfoGetRequest.php', array(
            'appkey' => $appkey,
            'secretKey' => $secretKey,
            'sessionKey' => $sessionKey,
            'tid' => $tid,          
        ));

    /*$resp = $this->request('http://121.199.174.216:30002/api/TradeInfo/GetTradeFullInfo', array(
            'appKey' => $appkey,
            'secretKey' => $secretKey,
            'sessionKey' => $sessionKey,
            'tradeId' => $tid,
        ));*/

        return $resp;
    }

    function GetTaoBaoRefreshTokenUrl($appkey, $secret, $sessionkey, $refreshToken) {
        $signs = array();
        $signs['appkey'] = $appkey;
        $signs['refresh_token'] = $refreshToken;
        $signs['sessionkey'] = $sessionkey;
        $sign = '';
        foreach ($signs as $key => $val) {
            $sign .= $key . $val;
        }
        $sign .= $secret;
        $sign = md5($sign, true);
        $len = strlen($sign);
        $signs['sign'] = '';

        for ($i = 0; $i < $len; $i++) {
            $signs['sign'] .= str_pad(dechex(ord($sign[$i])), 2, '0', STR_PAD_LEFT);
        }
        $signs['sign'] = strtoupper($signs['sign']);

        return "http://container.open.taobao.com/container/refresh?" . http_build_query($signs);
    }

    public function getTaobaoToken() {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $appkey = "23087578";
        $secretKey = "9091c68da02bddfcda0c8fb91458cf83";
        
          //$appkey = '23148888';
          //$secretKey = '6f2ace5e8e6f332dc667ea802852e95e';

         //$appkey = '23090235';
         //$secretKey = 'd11e4e30490f9f142f3b5dd6fae86ae2';

        $taobaouser = Application_Model_Taobaoapi::byUserAll();
        foreach ($taobaouser as $taobaoval) {
            $sessionKey = $taobaoval->sessionkey;
            $freshToken = $taobaoval->freshtoken;
            $retourl = $this->GetTaoBaoRefreshTokenUrl($appkey, $secretKey, $sessionKey, $freshToken);
            $t = file_get_contents($retourl);
            if (strpos($t, "error") > 0) {
                echo $taobaoval->taobaoname . "出现问题" . $sessionKey . $t . "<br>";
            } else {
                $v = json_decode($t);
                $taobaoval->freshtoken = $v->refresh_token;
                $taobaoval->sessionkey = $v->top_session;
                $taobaoval->save();
                echo $taobaoval->taobaoname . " sessionkey 有效期延长成功<br>";
            }
        }
        exit;
    }
    
     // 定义一个函数getIP()
    public function getIP()
    {
            global $ip;

            if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
            else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
            else if(getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
            else
            $ip = "Unknow";

            return $ip;
    }

     public function taobaowlprice($tid)
    {
        $appkey = "23087578";
        $secretKey = "9091c68da02bddfcda0c8fb91458cf83";
        
          //$appkey = '23148888';
          //$secretKey = '6f2ace5e8e6f332dc667ea802852e95e';

         //$appkey = '23090235';
         //$secretKey = 'd11e4e30490f9f142f3b5dd6fae86ae2';
        //'appkey'     => '23090235',
       // 'secretKey'  => 'd11e4e30490f9f142f3b5dd6fae86ae2',
        $pd = substr($tid, -4);
        $taobaoapi = Application_Model_Taobaoapi::getByTaoBaoSign($pd);
        $sessionKey = $taobaoapi->sessionkey;
        /*$c = new TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secretKey;
        $req = new TradeFullinfoGetRequest;
        $req->setFields("orders.status,orders.total_fee,post_fee");
        $req->setTid($tid);
        $resp = $c->execute($req, $sessionKey);*/

$resp = $this->request('http://127.0.0.1/tbsdk/TradeFullinfoGetRequest2.php', array(
            'appkey' => $appkey,
            'secretKey' => $secretKey,
            'sessionKey' => $sessionKey,
            'tid' => $tid,          
        ));

    /*$resp = $this->request('http://121.199.174.216:30002/api/TradeInfo/GetTradeFullInfo', array(
            'appKey' => $appkey,
            'secretKey' => $secretKey,
            'sessionKey' => $sessionKey,
            'tradeId' => $tid,
        ));*/

        return $resp;
    }

}
